<template>
  <div class="search-box">
    <!-- 搜索栏 事件监听 -->
    <form class='search' action="/">
      <van-search
        v-model="searchTxt"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus='isShowResults = false'
      />
    </form>
    <!-- 搜索结果 -->
    <SearchResults v-if="isShowResults" :searchTxt='searchTxt' />
    <!-- 搜索历史 -->
    <SearchHistory @search='onSearch' :histories='histories' v-else-if="!searchTxt" />
    <!-- 搜索联想建议 -->
    <SesrchSuggestion @search='onSearch' v-else :searchTxt='searchTxt' />
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchResults from './components/SearchResults.vue'
import SesrchSuggestion from './components/SesrchSuggestion.vue'
import { getItem, setItem } from '@/utils/storage.js'
export default {
  name: 'Search',
  data () {
    return {
      searchTxt: '',
      isShowResults: false,
      histories: getItem('SEARCH') || []
    }
  },
  components: {
    SearchHistory,
    SearchResults,
    SesrchSuggestion
  },
  created () {

  },
  watch: {
    histories () {
      setItem('SEARCH', this.histories)
    }
  },
  methods: {
    onSearch (val) {
      if (val.trim().length === 0) return
      const index = this.histories.indexOf(val)
      if (index !== -1) {
        this.histories.splice(index, 1)
      }
      this.histories.unshift(val)
      this.searchTxt = val
      this.isShowResults = true
    },
    onCancel () {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped lang='less'>
  .search-box {
    .van-search {
      background-color: #3296fa;
    }
    .van-search__action {
      color: #fff;
    }
  }
  .search {
    position: sticky;
    top: 0;
    z-index: 2;
  }
</style>
